package com.zheng.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zheng.dao.NxYthBillMapper;
import com.zheng.dto.CzsbBody;
import com.zheng.entity.NxYthBill;
import com.zheng.utils.NXHttpUtil;
import com.zheng.utils.base.ZhengUtil;
import com.zheng.utils.safeUtil.TranSM4Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName YthController
 * @Description 模拟一体化服务
 * @Author zhengchenggong
 * @Date 2020/12/8 4:24 下午
 * @Version 1.0
 **/
@RestController
@Transactional
public class YthController {

//    private static String longKey = "zXXjDaZj0DqCZuslDViC2N1yoJpUdAva";
    private static String longKey = "lTUc4gqaOjJ4K0vLOYirPMoK3T8BDCCn";
    private static String tempKey = "M8OMkOHKSnA9f2x2sfbxhkX441uOJvxT";

    @Autowired
    NxYthBillMapper nxYthBillDao;

    @RequestMapping("/SE/applyTempKey")
    public String applyTempKey(HttpServletRequest request) {

        String key = TranSM4Utils.encryptData_CBC(tempKey, longKey.substring(0, 16), longKey.substring(16));
        String token = UUID.randomUUID().toString().replace("-","");
        JSONObject data = new JSONObject();
        data.put("token",token);
        data.put("key",key);
        JSONObject res = new JSONObject();
        res.put("result","0");
        res.put("message","成功");
        res.put("data",data);
        String s = res.toJSONString();
        System.out.println("applyTempKey返回报文："+s);
        return s;

    }

//    @RequestMapping("/czsoc/remoting/nx/commonservice")
    @RequestMapping("/real/dial/commonservice")
    public String test_czsoc_commonservice(HttpServletRequest request, HttpServletResponse response,@RequestBody String req) throws Exception{
        System.out.println("test_czsoc_commonservice");
        System.out.println("解密前报文："+req);
        JSONObject res = null;
        try {
            String serverTempKey = this.getServerTempKey(request);
            String baowen = TranSM4Utils.decryptData_CBC(req, serverTempKey.substring(0, 16), serverTempKey.substring(16));
            System.out.println("解密后报文："+baowen);
            CzsbBody czsbBody = JSON.parseObject(baowen, CzsbBody.class);
            res = new JSONObject();
            if(czsbBody.getBus_method().equals("addRealPay")){//接收单据
                List<Map> datalist = czsbBody.getDatalist();
                datalist.forEach(e->{
                    e.put("status","00");
                    NxYthBill nxYthBill = ZhengUtil.mapUnderLineToHumpBean(e, NxYthBill.class);
                    nxYthBill.setInputTime(new Date());
                    nxYthBill.setUpdateTime(new Date());
                    nxYthBillDao.insert(nxYthBill);
                });
                res.put("result","0");
                res.put("message","成功");
            }else if (czsbBody.getBus_method().equals("commonQueryDataService")){//查询单据
                String[] pay_alloc_cert_ids = czsbBody.getConditions().get("pay_alloc_cert_id").split(",");
                List<NxYthBill> sta = nxYthBillDao.selectBatchIds(Arrays.asList(pay_alloc_cert_ids));
                List data = new ArrayList();
                sta.stream().forEach(e->{
                    Map map = new HashMap();
                    map.put("billcode",e.getPayAllocCertId());
                    map.put("auditcode","like");
                    map.put("auditname","李可");
                    map.put("status",e.getStatus());
                    map.put("pay_alloc_cert_id",e.getPayAllocCertId());
                    map.put("abolishdate",new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));
                    data.add(map);
                });
                res.put("result","0");
                res.put("message","成功");
                res.put("data",data);

            }else{
                res.put("result","1");
                res.put("message","报文异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.put("result","1");
            res.put("message",e.getMessage());
        }
        System.out.println("加密前返回："+res);
        String miwen = TranSM4Utils.encryptData_CBC(res.toJSONString(), tempKey.substring(0, 16), tempKey.substring(16));
        System.out.println("加密后返回："+miwen);
        return miwen;
    }

    //用长秘钥解析报文头得临时秘钥
    private String getServerTempKey(HttpServletRequest request) {
        String tempKey = null;
        try {
            String se_tempKey = request.getHeader("SE_tempKey");
            se_tempKey = se_tempKey==null?TranSM4Utils.encryptData_CBC(YthController.tempKey,YthController.longKey.substring(0,16),YthController.longKey.substring(16)):se_tempKey;
            System.out.println("请求方SE_tempKey=="+se_tempKey);
            System.out.println("长秘钥：" + longKey);
            tempKey = TranSM4Utils.decryptData_CBC(se_tempKey, longKey.substring(0, 16), longKey.substring(16));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析请求方临时秘钥失败");
        }
        return tempKey;
    }

    @RequestMapping("test")
    public String test(){
        QueryWrapper<NxYthBill> queryWrapper = new QueryWrapper();
        List<Map<String, Object>> res = nxYthBillDao.selectMaps(queryWrapper);
        return JSON.toJSONString(res);
    }

    //测试sendPayNotice 拨付通知接口
    public static void main(String[] args) {

        String req = "{\"province\":\"640000000\",\"year\":2021,\"datalist\":[{\"billcode\":\"H01_2021_00000138\",\"amt\":105000000,\"guid\":\"99524E20887D198B676FAC4BA3534F89\",\"pay_alloc_cert_id\":\"a6d5f973c25142f38f2d908d32cde19c\",\"rn\":1,\"status\":\"006\"}]}";
        try{
            doPost("http://127.0.0.1:8080/nxYthController/sendPayNotice",req);
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    private static Map doPost(String url,String req) throws Exception{
        System.out.println("加密前报文：" + req);
        //TODO 此处需要调用获取临时秘钥的方法
        String sm4Key = tempKey;
        String token = "111";
        Map header = packHeader(token);
        System.out.println("---sm4Key秘钥：" + sm4Key);
        String miwen = TranSM4Utils.encryptData_CBC(req, sm4Key.substring(0, 16), sm4Key.substring(16));
        System.out.println("加密后报文:" + miwen);
        String res = NXHttpUtil.doPost(url, header, miwen, 6000);
        System.out.println("解密前返回：" + res);
        String resCbc = TranSM4Utils.decryptData_CBC(res, sm4Key.substring(0, 16), sm4Key.substring(16));
        System.out.println("解密后返回：" + resCbc);
        Map resMap = JSON.parseObject(resCbc, Map.class);
        return resMap;
    }

    private static Map packHeader( String token) {
        Map header = new HashMap();
        header.put("Content-Type", "application/json");
        header.put("SE_sysCode", "YTH");//平台分配的业务系统编号
        header.put("SE_userId", "111");//平台分配的账号ID
        header.put("SE_password", "222");//平台分配的账号密码
        header.put("SE_targetSysCode", "2222");//目标系统编码
        header.put("SE_targetServiceCode", "44444");//目标接口编码
        header.put("SE_token", token);
        String SE_tempKey = TranSM4Utils.encryptData_CBC(tempKey, longKey.substring(0, 16), longKey.substring(16));
        header.put("SE_tempKey", SE_tempKey);
        System.out.println("Http-Header头信息："+ JSON.toJSONString(header));
        return header;
    }




}
